package com.train.course.service.impl;

import com.train.course.domain.VideoViewHistory;
import com.train.course.mapper.VideoViewHistoryMapper;
import com.train.course.service.IVideoViewHistoryService;
import com.train.course.vo.HistoryVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * 视频观看历史 服务层实现
 */
@Service
public class VideoViewHistoryServiceImpl implements IVideoViewHistoryService {

    @Autowired
    private VideoViewHistoryMapper videoViewHistoryMapper;

    /**
     * 上报观看进度
     */
    @Override
    @Transactional
    public boolean reportProgress(Long userId, Long episodeId, Integer progress) {
        // 查询是否已有观看记录
        VideoViewHistory existingHistory = videoViewHistoryMapper.selectVideoViewHistoryByUserAndEpisode(userId, episodeId);
        
        if (existingHistory != null) {
            // 更新现有记录
            existingHistory.setProgress(progress);
            existingHistory.setPercentage(progress * 100 / existingHistory.getDuration());
            existingHistory.setLastViewTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            return videoViewHistoryMapper.updateVideoViewHistory(existingHistory) > 0;
        } else {
            // 插入新记录（需要先获取视频时长）
            VideoViewHistory newHistory = new VideoViewHistory();
            newHistory.setUserId(userId);
            newHistory.setEpisodeId(episodeId);
            newHistory.setProgress(progress);
            newHistory.setDuration(0); // 这里需要从 video_episode 表获取，暂时设为0
            newHistory.setPercentage(0);
            newHistory.setLastViewTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            
            return videoViewHistoryMapper.insertVideoViewHistory(newHistory) > 0;
        }
    }

    /**
     * 查询观看历史列表（下滑刷新）
     */
    @Override
    public List<HistoryVO> getHistoryList(Long userId, Long lastHistoryId, Integer pageSize) {
        List<HistoryVO> historyList = videoViewHistoryMapper.selectHistoryListWithEpisode(userId, lastHistoryId, pageSize);
        
        // 为每条记录计算分组标识
        for (HistoryVO history : historyList) {
            history.setGroupLabel(calculateGroupLabel(history.getLastViewTime()));
        }
        
        return historyList;
    }

    /**
     * 计算分组标识
     */
    private String calculateGroupLabel(java.util.Date lastViewTime) {
        if (lastViewTime == null) {
            return "earlier";
        }
        
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime viewTime = lastViewTime.toInstant().atZone(java.time.ZoneId.systemDefault()).toLocalDateTime();
        
        // 今天
        if (viewTime.toLocalDate().equals(now.toLocalDate())) {
            return "today";
        }
        
        // 昨天
        if (viewTime.toLocalDate().equals(now.toLocalDate().minusDays(1))) {
            return "yesterday";
        }
        
        // 近7天
        if (viewTime.isAfter(now.minusDays(7))) {
            return "last7days";
        }
        
        // 更早
        return "earlier";
    }
}
